import { getProblemPieceStatisticsPageApi, problemPieceStatisticsExcelApi } from "@/api/reportManager/problemStatistics";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { computed, Ref } from "vue";
export default function OperationHook(state: { searchForm: ProblemStatistics.SearchForm; tableData: Ref<Array<ProblemStatistics.ListRows>>; loading: Ref<boolean>; tableRef: Ref<any> }) {
  const { searchForm, tableData, loading, tableRef } = state;
  const selectRows = computed<Array<ProblemStatistics.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const getData = () => {
    const params = {
      ...getParams()
    };

    loading.value = true;
    return getProblemPieceStatisticsPageApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const getParams = () => {
    const { waybillNumList, problemPieceTypeList, bizIdList, createByList, time, total, pageNum, pageSize, customerIdList } = searchForm;
    const params: ProblemStatistics.SearchParams = {
      waybillNumList: [],
      customerIdList,
      problemPieceTypeList,
      bizIdList,
      createByList,
      createStartTime: time.length ? dayjs(time[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      createEndTime: time.length ? dayjs(time[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      total,
      pageNum,
      pageSize
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    return params;
  };

  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  //导出
  const exportHandle = () => {
    const params: { list: ProblemStatistics.ListRows[] } | ProblemStatistics.SearchParams = selectRows.value.length ? { list: selectRows.value } : { ...getParams() };
    loading.value = true;
    return problemPieceStatisticsExcelApi(params)
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("创建任务成功，请前往导出中心下载！");
          getData();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  return {
    searchHandle,
    getData,
    exportHandle
  };
}
